import TokenReducer from './token';
import UiReducer from './ui';

class Reducer {
    reducerTable = {};
    state = {};

    asFunction() {
        const _this = this;
        return (state, action) => {
            return _this.handleAction(state, action);
        };
    }

    handleAction(state, action) {
        state = state || this.state;
        const {type} = action;
        const dotIndex = type.indexOf('.');
        if (dotIndex < 0) {
            console.log('Invalidate action type', type, action);
            return {
                ...state
            };
        }
        const actionName = type.substr(0, dotIndex);
        if (!(actionName in this.reducerTable)) {
            console.log('Cant find action reducer', action);
            return {
                ...state
            };
        }
        const subState = this.reducerTable[actionName].handleAction(type, action);
        const res = {
            ...this.state,
        };
        res[actionName] = subState;
        return res;
    }

    register(reducer) {
        const name = reducer.getName();
        this.state[name] = reducer.getState();
        this.reducerTable[name] = reducer;
    }
}

const reducer = new Reducer();
new TokenReducer().autoRegister(reducer);
new UiReducer().autoRegister(reducer);

export default reducer.asFunction();